package com.intelligent.bot.api;

import com.alibaba.fastjson.JSONObject;
import com.intelligent.bot.annotate.AvoidRepeatRequest;
import com.intelligent.bot.base.exception.E;
import com.intelligent.bot.base.result.B;
import com.intelligent.bot.constant.CommonConst;
import com.intelligent.bot.utils.sys.ImgUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/base")
@Log4j2
@Transactional(rollbackFor = E.class)
public class BaseApi {

    @Value("${imgUrl}")
    private String imgUrl;


    @RequestMapping(value = "/upload/file", name = "上传")
    @AvoidRepeatRequest()
    public B<JSONObject> upload(MultipartFile file) throws IOException {
        String oldFileName = Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().lastIndexOf("."));
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = ImgUtil.uploadMultipartFile(file, oldFileName,fileSuffix);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url",imgUrl + fileName);
        jsonObject.put("fileName",oldFileName);
        jsonObject.put("filePath",fileName);
        return B.okBuild(jsonObject);
    }
}
